<template>
  <div class="matrices-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-select
              v-model="courseFilter"
              placeholder="课程筛选"
              clearable
              @change="handleSearch"
              style="width: 200px"
            >
              <el-option
                v-for="course in courses"
                :key="course.id"
                :label="course.courseName"
                :value="course.id"
              />
            </el-select>
            
            <el-select
              v-model="indicatorFilter"
              placeholder="指标点筛选"
              clearable
              @change="handleSearch"
              style="width: 200px"
            >
              <el-option
                v-for="indicator in indicators"
                :key="indicator.id"
                :label="indicator.indicatorName"
                :value="indicator.id"
              />
            </el-select>
            
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
          
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            v-if="userStore.isAdmin"
          >
            新增支撑关系
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="matrices"
        border
        style="width: 100%"
      >
        <el-table-column label="课程" min-width="200">
          <template #default="{ row }">
            {{ getCourseName(row.courseId) }}
          </template>
        </el-table-column>
        
        <el-table-column label="指标点" min-width="200">
          <template #default="{ row }">
            {{ getIndicatorName(row.indicatorId) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="supportLevel" label="支撑强度" width="120">
          <template #default="{ row }">
            <el-tag :type="getSupportLevelType(row.supportLevel)">
              {{ row.supportLevel }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="weight" label="支撑权重" width="120">
          <template #default="{ row }">
            {{ row.weight }}
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
              v-if="userStore.isAdmin"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
              v-if="userStore.isAdmin"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 支撑矩阵表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增支撑关系' : '编辑支撑关系'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="课程" prop="courseId">
          <el-select
            v-model="form.courseId"
            placeholder="请选择课程"
            style="width: 100%"
          >
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.courseName"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="指标点" prop="indicatorId">
          <el-select
            v-model="form.indicatorId"
            placeholder="请选择指标点"
            style="width: 100%"
          >
            <el-option
              v-for="indicator in indicators"
              :key="indicator.id"
              :label="indicator.indicatorName"
              :value="indicator.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="支撑强度" prop="supportLevel">
          <el-select
            v-model="form.supportLevel"
            placeholder="请选择支撑强度"
            style="width: 100%"
          >
            <el-option label="高(H)" value="H" />
            <el-option label="中(M)" value="M" />
            <el-option label="低(L)" value="L" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="支撑权重" prop="weight">
          <el-input-number
            v-model="form.weight"
            :min="0"
            :max="1"
            :precision="2"
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import request from '../api/request'

const userStore = useUserStore()
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const courseFilter = ref('')
const indicatorFilter = ref('')
const matrices = ref([])
const courses = ref([])
const indicators = ref([])

const form = reactive({
  id: null,
  courseId: null,
  indicatorId: null,
  supportLevel: '',
  weight: 0
})

const rules = {
  courseId: [
    { required: true, message: '请选择课程', trigger: 'change' }
  ],
  indicatorId: [
    { required: true, message: '请选择指标点', trigger: 'change' }
  ],
  supportLevel: [
    { required: true, message: '请选择支撑强度', trigger: 'change' }
  ],
  weight: [
    { required: true, message: '请输入支撑权重', trigger: 'blur' }
  ]
}

const fetchMatrices = async () => {
  try {
    loading.value = true
    const res = await request.get('/api/course-support-matrices', {
      params: {
        courseId: courseFilter.value,
        indicatorId: indicatorFilter.value
      }
    })
    matrices.value = res.data
  } catch (error) {
    console.error('获取支撑矩阵列表失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchCourses = async () => {
  try {
    const res = await request.get('/api/courses')
    courses.value = res.data
  } catch (error) {
    console.error('获取课程列表失败:', error)
  }
}

const fetchIndicators = async () => {
  try {
    const res = await request.get('/api/indicators')
    indicators.value = res.data
  } catch (error) {
    console.error('获取指标点列表失败:', error)
  }
}

const handleSearch = () => {
  fetchMatrices()
}

const resetSearch = () => {
  courseFilter.value = ''
  indicatorFilter.value = ''
  fetchMatrices()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    courseId: null,
    indicatorId: null,
    supportLevel: '',
    weight: 0
  })
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    id: row.id,
    courseId: row.courseId,
    indicatorId: row.indicatorId,
    supportLevel: row.supportLevel,
    weight: row.weight
  })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该支撑关系吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.delete(`/api/course-support-matrices/${row.id}`)
    ElMessage.success('删除成功')
    fetchMatrices()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (dialogType.value === 'add') {
      await request.post('/api/course-support-matrices', form)
      ElMessage.success('新增成功')
    } else {
      await request.put(`/api/course-support-matrices/${form.id}`, form)
      ElMessage.success('编辑成功')
    }
    
    dialogVisible.value = false
    fetchMatrices()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

const getCourseName = (courseId) => {
  const course = courses.value.find(c => c.id === courseId)
  return course ? course.courseName : ''
}

const getIndicatorName = (indicatorId) => {
  const indicator = indicators.value.find(i => i.id === indicatorId)
  return indicator ? indicator.indicatorName : ''
}

const getSupportLevelType = (level) => {
  switch (level) {
    case 'H':
      return 'success'
    case 'M':
      return 'warning'
    case 'L':
      return 'info'
    default:
      return ''
  }
}

const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

onMounted(async () => {
  await Promise.all([
    fetchMatrices(),
    fetchCourses(),
    fetchIndicators()
  ])
})
</script>

<style scoped>
.matrices-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  gap: 10px;
}
</style> 